package com.kjjt.controller;

import com.kjjt.exception.BizException;
import com.kjjt.util.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(ConstraintViolationException.class)
    public Result handle(ConstraintViolationException ex) {
        return Result.fail("参数验证失败：" + ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handle(MethodArgumentNotValidException ex) {
        List<ObjectError> allErrors = ex.getAllErrors();

        List<String> errorMessageList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            errorMessageList.add(allError.getDefaultMessage());
        }

        return Result.fail("参数验证失败：" + errorMessageList);
    }

    @ExceptionHandler(BizException.class)
    public Result handleBiz(BizException e) {
        return Result.fail(e.getMessage());
    }

}
